﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using LYMesApi.Util;
using Newtonsoft.Json;
using System.Web.Script.Serialization;
using System.Text;
using System.Web;
using System.IO;
using System.Security;
using System.Configuration;
using SendIndustrialNetwork;
using Newtonsoft.Json.Linq;
using LYMesApi.Models;
using LYMesApi.Service;
using StackExchange.Redis;

namespace LYMesApi.Controllers
{
    public class DefaultController : ApiController
    {
        private static RedisHelper redis = new RedisHelper();
        private const String dcKey = "dcReceive";
        public string dataCenterHost = ConfigurationManager.AppSettings["dataCenterHost"].ToString();//数据中心地址

        public class data
        {
            public string appId { set; get; }
            public string password { set; get; }
        }
        // 测试请求接口地址 api/default/Get
        [HttpGet]
        public IEnumerable<string> Get()
        {
            test();
            return new string[] { "value1", "value2" };
        }

        // 测试请求接口地址 api/default/testApi
        [HttpPost]
        public HttpResponseMessage testApi(string strMessage, Byte[] fileinstance)
        {
            result r = new result { code = "200", msg = "认证成功:" + strMessage };
            return toJson(r);
        }

        // 接收数据中心推送接口 api/default/AcceptDCMessage
        [HttpPost]
        public HttpResponseMessage AcceptDCMessage([FromBody] ReceivedModel jsondata)
        {
            LogHelp.WriteLog("接收到数据中心推送消息结果：" + JsonConvert.SerializeObject(jsondata));
            string resmsg = "ok";
            if (String.IsNullOrEmpty(jsondata.BusinessID))
            {
                resmsg = "businessid不存在";
                LogHelp.WriteLog("businessid不存在");
            }
            else
            {

                //将收到的任务存到redis中，异步数据处理 add:wangjh 20241111
                redis.PushListLeft(dcKey, JsonConvert.SerializeObject(jsondata));

                /*--------------------------------
                 * dtype：10：表结构，20：表数据，30：文件
                 --------------------------------*/
                //if (jsondata.DType == "20")
                //{
                //    //调用数据中心的接口，下载文件得到文件流
                //    string getFileDataUrl = string.Format("http://{0}:8080/lygkdc-service/lygk/dc/static/{1}", dataCenterHost, jsondata.BusinessID);
                //    string resJson = HttpUtils.Get(getFileDataUrl);
                //    LogHelp.WriteLog(string.Format("【businessid：{0}】获取的结果：{1}", jsondata.BusinessID, resJson));
                //    //转为强类型对象
                //    DCDataModel resModel = JsonConvert.DeserializeObject<DCDataModel>(resJson);
                //    if (resModel.IsZip == "1")
                //    {
                //        string decodeZipData = EncryptHelper.DecompressString(resModel.ZipData);//将压缩内容解压，获取要同步的表数据
                //        LogHelp.WriteLog(string.Format("【businessid：{0}】获取的结果：{1}", jsondata.BusinessID, resJson));
                //        resModel.Items = JsonConvert.DeserializeObject<List<Dictionary<string, string>>>(decodeZipData);
                //    }
                //    DBSyncCommonService dcService = new DBSyncCommonService();
                //    resmsg = dcService.DealDataTableSync(resModel);
                //}
                //else if (jsondata.DType == "10" || jsondata.DType == "30")
                //{
                //    //存为文件
                //    string saveFilePath = ConfigurationManager.AppSettings["saveFilePath"].ToString();
                //    String filePath = saveFilePath + "/" + jsondata.DType + DateTime.Now.ToString("yyyy-MM-ddHHmmss") + ".json";
                //    File.WriteAllText(filePath, "");

                //}
            }

            return toJson(resmsg);
        }

        public void test()
        {
            string resJson = "{\"zipdata\":\"H4sIAAAAAAAAAIuuVipJLS5RslJ6smPts2ntSjpKAUH+wSGOIaHBQEFHID802DXIzx/IMTQyBnI9XYBMAwNDpVqdatxqDQyMEGqNlGpjAdCioiFpAAAA\",\"qianfaren\":\"wangwu\",\"toappid\":\"lydl.mes\",\"shenpiren\":\"lisi\",\"iszip\":\"1\",\"fromappid\":\"lyiot.rbmes\",\"trantype\":\"10\",\"updtype\":\"10\",\"tablename\":\"\",\"wenjianqicaoren\":\"zhangsan\"}";
            //转为强类型对象
            DCDataModel resModel = JsonConvert.DeserializeObject<DCDataModel>(resJson);
            if (resModel.IsZip == "1")
            {
                string decodeZipData = EncryptHelper.DecompressString(resModel.ZipData);//将压缩内容解压，获取要同步的表数据
                resModel.Items = JsonConvert.DeserializeObject<List<Dictionary<string, string>>>(decodeZipData);
                LogHelp.WriteLog(string.Format("{0}", JsonConvert.SerializeObject(resModel)));
            }
            return;
        }

        [HttpPost]
        public HttpResponseMessage AcceptDCMessageTest()
        {
            string resmsg = "ok";
            try
            {
                string getFileDataUrl = string.Format("http://{0}:8080/lygkdc-service/lygk/dc/static/1843826181204430849", dataCenterHost);//文件地址
                string resJson = HttpUtils.Get(getFileDataUrl);
                //string resJson = "{\"qianfaren\":\"wangwu\",\"toappid\":\"lydl.mes\",\"dtype\":\"20\",\"shenpiren\":\"lisi\",\"fromappid\":\"lyiot.rbmes\",\"trantype\":\"10\",\"updtype\":\"10\",\"tablename\":\"ContainerStepWorkReport\",\"items\":[{\"CONTAINERSTEPDISPATCHID\":\"14aba41e-5902-4fea-87b3-5aed4532ea04\",\"CONTAINERID\":\"0004108000015b79\",\"PROSTATUS\":\"A\",\"ISUSE\":false,\"QTY\":10.0,\"WORKERID\":\"user-infodba-123456\",\"RESOURCEID\":\"0005d28000002bc5\",\"WORKFLOWSTEPID\":\"00074e80000f665b\",\"CREATEDATE\":\"2024-08-28 16:23:00\",\"STEPINFOID\":\"4800b0800001034a\",\"CONTAINERSTEPWORKREPORTID\":\"4f3d53e7ea86412a9605523ff594102d\",\"FACTORYID\":\"0004e28000002d08\"}],\"wenjianqicaoren\":\"zhangsan\"}";
                //LogHelp.WriteLog(string.Format("【businessid：1828260755691208706】获取的结果：{0}", resJson));
                DCDataModel resModel = JsonConvert.DeserializeObject<DCDataModel>(resJson);//反序列获取的JSON
                //string decodeZipData = EncryptHelper.DecompressString(result.ZipData);//将压缩内容解压,获取要同步的表数据
                //LogHelp.WriteLog(string.Format("【businessid：{0}】，【表名：{1}】待同步的表数据：{2}", businessid, result.TableName, decodeZipData));
                //List<Dictionary<string, string>> dataList = JsonConvert.DeserializeObject<List<Dictionary<string, string>>>(decodeZipData);//反序列JSON
                DBSyncCommonService dcService = new DBSyncCommonService();
                resmsg = dcService.DealDataTableSync(resModel);//处理表数据
            }
            catch (Exception ex)
            {
                resmsg = ex.Message;
                LogHelp.WriteLog(resmsg);
            }

            return toJson(resmsg);
        }

        // GET api/default1/5
        [HttpPost]
        public HttpResponseMessage appAuth([FromBody] data dt)
        {
            LogHelp.SetConfig();
            LogHelp.WriteLog("请求登录：" + new JavaScriptSerializer().Serialize(dt));
            result r = new result();
            var token = CreateToken();
            CacheHelper.SetToken("token", token);
            r.code = "200";
            r.token = token;
            r.msg = "认证成功";
            if (dt.appId != appId)
            {
                r.code = "101";
                r.msg = "认证失败：应用ID不匹配,请联系系统管理员";
                r.token = null;
            }
            if (dt.password != SM3Util.ToSM3HexStr(password))
            {
                r.code = "101";
                r.msg = "认证失败：应用密码不匹配,请联系系统管理员";
                r.token = null;
            }

            LogHelp.WriteLog("请求登录结果：" + toJson(r));
            return toJson(r);
        }

        [HttpPost]
        public HttpResponseMessage fileUpload()
        {
            result r = new result();
            var token = CacheHelper.GetToken("token");
            if (string.IsNullOrWhiteSpace(token))
            {
                r.code = "101";
                r.msg = "token凭证失效，文件上传失败";
                LogHelp.WriteLog("接收文件:" + r.msg);
                return toJson(r);
            }
            try
            {
                Stream stream = System.Web.HttpContext.Current.Request.InputStream;
                //StreamReader reader = new StreamReader(stream);
                StringBuilder dic = new StringBuilder();
                var headers = HttpContext.Current.Request.Headers;
                Dictionary<string, string> headDic = new Dictionary<string, string>();
                foreach (string key in headers.Keys)
                {
                    dic.Append("----[" + key + "---" + System.Web.HttpUtility.UrlDecode(headers.GetValues(key).First()) + "]--");
                    headDic.Add(key, System.Web.HttpUtility.UrlDecode(headers.GetValues(key).First()));
                }
                LogHelp.WriteLog("接收文件,请求头信息：" + dic.ToString());
                var dtoken = JWT.JsonWebToken.DecodeToObject<Dictionary<string, string>>(headDic["Token"], SecretKey);
                var Tpassword = dtoken["password"].ToString();
                var TappId = dtoken["appId"].ToString();
                if (Tpassword != SM3Util.ToSM3HexStr(password) || TappId != appId)
                {
                    r.code = "101";
                    r.msg = "非法用户,禁止上传文件";
                    LogHelp.WriteLog("接收文件:" + r.msg);
                    return toJson(r);
                }
                if (stream.Length > 0)
                {
                    var absolutePath = AppDomain.CurrentDomain.BaseDirectory + "files\\";
                    if (!Directory.Exists(absolutePath))
                    {
                        Directory.CreateDirectory(absolutePath);
                    }
                    var fileType = "";
                    var bytes = new byte[stream.Length];
                    stream.Read(bytes, 0, bytes.Length);
                    //前两个字节代表文件类型,这里以 JPG 类型为例
                    var bs = bytes[0].ToString() + bytes[1].ToString();
                    if (headDic.ContainsKey("FileName")) { fileType = headDic["FileName"].ToString(); }
                    var path = absolutePath + DateTime.Now.ToString("yyyyMMddhhmmss") + "_" + fileType;
                    using (FileStream fs = new FileStream(path, FileMode.Create, FileAccess.Write))
                    {
                        fs.Write(bytes, 0, bytes.Length);
                    }
                    LogHelp.WriteLog("接收文件成功：" + path);
                }
                r.code = "200";
                r.msg = "文件上传成功";
            }
            catch (Exception ex)
            {
                LogHelp.WriteError(ex.Message, ex);
                r.code = "101";
                r.msg = "文件上传失败：" + ex.Message;
            }
            return toJson(r);
        }

        public static string Post(string Url, string jsonParas)
        {
            string strURL = Url;
            //创建一个HTTP请求
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(strURL);
            //Post请求方式
            request.Method = "POST";
            //内容类型
            request.ContentType = "application/json";

            //设置参数，并进行URL编码

            string paraUrlCoded = jsonParas;//System.Web.HttpUtility.UrlEncode(jsonParas);

            //将Json字符串转化为字节
            byte[] payload = System.Text.Encoding.UTF8.GetBytes(paraUrlCoded);

            //设置请求的ContentLength
            request.ContentLength = payload.Length;
            //发送请求，获得请求流

            Stream writer;
            try
            {
                writer = request.GetRequestStream();//获取用于写入请求数据的Stream对象
            }
            catch (Exception)
            {
                writer = null;
                Console.Write("连接服务器失败!");
            }
            //将请求参数写入流
            writer.Write(payload, 0, payload.Length);
            writer.Close();//关闭请求流
            // String strValue = "";//strValue为http响应所返回的字符流
            HttpWebResponse response;
            try
            {
                //获得响应流
                response = (HttpWebResponse)request.GetResponse();
                Stream s = response.GetResponseStream();
                //  Stream postData = Request.InputStream;
                StreamReader sRead = new StreamReader(s);
                string postContent = sRead.ReadToEnd();
                sRead.Close();
                return postContent;//返回Json数据
            }
            catch (WebException ex)
            {
                response = ex.Response as HttpWebResponse;
                return "error";
            }

        }

        #region MyRegion
        public static string SecretKey = "LYMES#@!";//这个服务端加密秘钥 属于私钥
        public static string password = ConfigurationManager.AppSettings["password"].ToString();
        public static string appId = ConfigurationManager.AppSettings["appId"].ToString();
        public static string CreateToken()
        {
            var payload = new Dictionary<string, dynamic>
                {
                    {"password",SM3Util.ToSM3HexStr(password)},//自定义字段 用于存放当前登录人账户信息
                    {"appId",appId},//自定义字段 用于存放当前登录人登录密码信息
                };
            return JWT.JsonWebToken.Encode(payload, SecretKey, JWT.JwtHashAlgorithm.HS256);
        }
        public class result
        {
            public string code { set; get; }
            public string token { set; get; }
            public string msg { set; get; }
        }
        public static HttpResponseMessage toJson(Object obj)
        {
            String str;
            if (obj is String || obj is Char)
            {
                str = obj.ToString();
            }
            else
            {
                JavaScriptSerializer serializer = new JavaScriptSerializer();
                str = serializer.Serialize(obj);
            }
            HttpResponseMessage result = new HttpResponseMessage { Content = new StringContent(str, Encoding.GetEncoding("UTF-8"), "application/json") };
            return result;
        }
        #endregion
    }
}
